<template>
    <div class="container formScene">
        <!-- header -->
        <div class="headers">
            <div class="header_left">
                <el-radio-group
                    v-model="type"
                    size="small"
                >
                    <el-radio-button
                        label="0">系统默认</el-radio-button>
                    <el-radio-button
                        label="1">自定义</el-radio-button>
                </el-radio-group>
            </div>
            <div class="header_right">
                <el-button
                    type="primary"
                    size="small"
                    @click="fnAddForm()"
                    v-if="type ==0"
                >添加表单</el-button>
                <el-button
                    type="primary"
                    size="small"
                    v-if="type ==1"
                    @click=" fnCreateScren() "
                >新建</el-button>
                <el-popover
                    placement="top-start"
                    width="230"
                    trigger="hover"
                    content="可用来链接表单类型的banner"
                    v-if="type ==1"
                >
                    <el-button
                        slot="reference"
                        class="reference"
                        size="small"
                    >
                        <i
                            class="el-icon-question"
                            style="fontSize:22px"
                        />
                    </el-button>
                </el-popover>
            </div>
        </div>
        <!-- /header -->

        <!-- 系统默认 -->
        <div v-if="type == 0">
            <div
                v-for="(item,index) in tableData"
                :key="index"
            >
                <p class="el-table-title">
                    <el-tag
                        v-if="item.scene == 'stuagent'"
                        size="small"
                    >掌大精英可见</el-tag>
                    <el-tag
                        size="small"
                        v-if="item.scene == 'stuagent_fans'"
                    >掌大精英和粉丝可见</el-tag>
                    <el-tag
                        size="small"
                        v-if="item.scene == 'student'"
                    >所有用户可见</el-tag>
                </p>
                <el-table
                    :data="item.custom_form_list"
                    style="width: 100%;"
                    border
                    @sort-change="handleSortChanged"
                >
                    <el-table-column
                        prop="title"
                        label="表单名称"
                        show-overflow-tooltip
                        :formatter="emptyFormatter"
                        align="left"
                    />
                    <el-table-column
                        prop="form_no"
                        label="表单编号"
                        show-overflow-tooltip
                        :formatter="emptyFormatter"
                        align="left"
                        :width="150"
                    />
                    <el-table-column
                        prop="form_item_count"
                        label="表单题量"
                        show-overflow-tooltip
                        :formatter="emptyFormatter"
                        align="left"
                    />
                    <el-table-column
                        prop="view_count"
                        label="浏览量"
                        show-overflow-tooltip
                        align="left"
                    />
                    <el-table-column
                        prop="submit_count"
                        label="提交量"
                        show-overflow-tooltip
                        align="left"
                    />
                    <el-table-column
                        prop="user_name"
                        label="创建人"
                        show-overflow-tooltip
                        :formatter="emptyFormatter"
                        align="left"
                        :width="150"
                    />
                    <el-table-column
                        prop="create_time"
                        label="创建时间"
                        show-overflow-tooltip
                        :formatter="emptyFormatter"
                        align="left"
                        :width="160"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.create_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm') }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="type"
                        min-width="80"
                        label="预览"
                        align="left"
                    >
                        <template slot-scope="scope">
                            <el-popover
                                placement="bottom"
                                title="扫描下方二维码"
                                width="200"
                                popper-class="preview-qr"
                                trigger="hover"
                            >
                                <div class="preview-qr-wrap">
                                    <img :src="fnSetQrLink(scope.row)" >
                                </div>
                                <el-button
                                    slot="reference"
                                    type="text"
                                >预览</el-button>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        fixed="right"
                    >
                        <template slot-scope="scope">
                            <span
                                class="curse-add"
                                @click="fnRemoveFoem(item, scope.row)"
                            >移除</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <!-- /系统默认 -->

        <!-- 自定义 -->
        <el-table
            :data="customList"
            style="width: 100%;"
            height="100%"
            border
            v-if=" type == 1 "
        >
            <el-table-column
                label="序号"
                type="index"
                :width="120"
            />
            <el-table-column
                prop="scene_key"
                label="场景名"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="left"
            />
            <el-table-column
                prop="title"
                label="场景标题"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="left"
            />
            <el-table-column
                prop="create_time"
                label="创建时间"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="left"
            >
                <template slot-scope='scope'>
                    {{ scope.row.create_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm') }}
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
            >
                <template slot-scope="scope">
                    <span
                        class="curse-add"
                        @click="fnEditScren(scope.row)"
                    >编辑</span>
                    <span
                        class="curse-add"
                        @click="fnDeleteScren(scope.row)"
                    >删除</span>
                </template>
            </el-table-column>
        </el-table>
        <!-- /自定义 -->

        <!-- 新建场景 -->
        <el-dialog
            title="新增场景"
            :visible.sync="dialogVisibleAdd"
            width="500px"
            :close-on-click-modal="false"
        >
            <div class="el-screnn-dialog">
                <p style="white-space: nowrap;marginRight: 10px">表单场景名称</p>
                <el-input
                    v-model="addScrenn"
                    placeholder="请输入场景名称"
                    size="small"
                />
            </div>
            <span
                slot="footer"
                class="dialog-footer">
                <el-button
                    size="small"
                    @click="dialogVisibleAdd = false">取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="fnConfirmScrenn()"
                >确 定</el-button>
            </span>
        </el-dialog>
        <!-- /新建场景 -->

        <!-- dialog -->
        <el-dialog
            title="添加表单"
            width="400px"
            custom-class="schedule-dialog"
            :visible.sync="showAddDialog"
            :close-on-click-modal="ifModel"
        >
            <div class='dialog_cont'>
                <p style="marginRight: 10px;white-space: nowrap">表单场景</p>
                <el-select
                    v-model="sceneType"
                    placeholder="请选择"
                    style="width:100%"
                    size="small"
                >
                    <el-option
                        v-for="item in sceneList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </div>
            <div class="dialog_cont">
                <p style="marginRight: 10px;white-space: nowrap">表单名称</p>
                <el-select
                    v-model="simple"
                    filterable
                    placeholder="请选择"
                    size="small"
                    style="width:100%"
                    :disabled="ifSimple"
                    @change="fnGetSimaple()"
                >
                    <el-option
                        v-for="item in simpleList"
                        :key="item.form_no"
                        :label="item.title"
                        :value="item.form_no"
                    />
                </el-select>
            </div>
            <div
                :key="tag"
                v-for="tag in dynamicTags">
                <el-checkbox
                    v-model="checked"
                    style="margin-left: 36px;margin-right: 10px;"/>
                <el-tooltip
                    class="item"
                    effect="dark"
                    :content="tag"
                    placement="top">
                    <div class="text_form">{{ tag }}</div>
                </el-tooltip>
                <el-tooltip
                    class="item"
                    effect="dark"
                    :content="form_no"
                    placement="top">
                    <div class="text_form">{{ form_no }}</div>
                </el-tooltip>
                <i
                    class="el-icon-delete"
                    @click="deleteForm"/>
            </div>
            <span
                slot="footer"
                class="dialog-footer">
                <el-button
                    @click="showAddDialog = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    :disabled="!checked"
                    @click="subMitForm()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- dialog -->

        <!-- /分页 -->
        <div
            class="pagination-wrapper clearfix"
            v-if="type==1"
        >
            <el-pagination
                background
                layout="total, prev, pager, next"
                :current-page.sync="page.now_page"
                :total="page.total_count"
                :page-size="page.page_size"
                @current-change="getCustomList"
            />
        </div>
    </div>
</template>

<script>
/**
 * @param   {Boolean}   showAddDialog       //弹窗开关
 * @param   {Array}     list                //表单数据源
 * @param   {Object}    tableData           //当前显示表单数据
 * @param   {Array}     tableData           //当前显示表单数据
 * @param   {Number}    type                //可查看表单类型  0、1、2
 * @param   {Array}     simpleList          //添加表单列表
 * @param   {String}    form_no             //表单编号
 * @param   {Boolean}   ifModel             //是否可点击蒙层关闭弹窗
 * @param   {Boolean}   ifSimple            //是否可选择表单
 */
export default {
    data () {
        return {
            scene: '',
            typeModel: '',
            addScrenn: '',
            dialogVisibleAdd: false,
            sceneType: '',
            sceneList: [{
                value: 'stuagent',
                label: '掌大精英可见'
            },{
                value: 'stuagent_fans',
                label: '掌大精英和粉丝可见'
            },{
                value: 'student',
                label: '所有用户可见'
            }],
            customList: [],
            checked: true,
            ifSimple: false,
            ifModel: false,
            form_no: '',
            dynamicTags: [],
            simple: '',
            simpleList: [],
            type: 0,
            tableData: [],
            list: {
                stuagent_fans: [],
                stuagent: [],
                student: []
            },
            showAddDialog: false,
            filterData: {
                sort_field: '',
                sort_type: ''
            },
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            }
        };
    },
    watch: {
        showAddDialog (val) {
            if (!val) {
                this.ifSimple = false;
                this.dynamicTags = [];
                this.simple = '';
                this.sceneType = '';
            }
        },
        dialogVisibleAdd (val) {
            if (!val) {
                this.addScrenn = '';
            }
        }
    },
    created () {
        this.setHeader();
        this.getTableData();
        this.getSImpleList();
        this.getCustomList();
    },
    methods: {
        /**
         * 设置表单header
         */
        setHeader () {
            this.$store.commit('SET_HEADER', [{title: "APP后台",},{title: '自定义表单'},{title: "表单场景"}]);
        },

        /**
         * 获取表单列表
         */
        getSImpleList () {
            this.$post('/student/custom_form%5Cget_simple_list',{},resp => {
                if (resp.code == 1) {
                    this.simpleList = [];
                    resp.data.list.map(item=>{
                        this.simpleList.push({
                            title: item.title,
                            form_no: item.title + '&' + item.form_no
                        });
                    });
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'waring',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 获取表格数据
         */
        getTableData (page) {
            this.$post('/student/custom_form%5Cget_scene_form_list', {}, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'waring',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 获取自定义表单列表
         */
        getCustomList (page) {
            this.$post('/student/custom_form_custom_scene%5Cget_list', {
                page_id: page || this.page.now_page
            }, resp => {
                if (resp.code == 1) {
                    this.customList = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                }
            });
        },

        /**
         * 预览表单
         */
        fnSetQrLink(row) {
            let base = this.$baseUrl;
            let ticket = localStorage.getItem('sessionTicket');
            let url = `${this.$studentBaseUrl}/pages/common/questionnaire?preview_key=${row.preview_key}`;

            let link = `${base}/__local/common%5Cqrcode?content=${url}&__ticket=${ticket}`;

            return link;
        },

        /**
         * 新建表单
         */
        fnCreateScren () {
            this.typeModel = 'add';
            this.dialogVisibleAdd = !this.dialogVisibleAdd;
        },

        /**
         * 编辑表单场景
         */
        fnEditScren (row) {
            this.scene = row.scene_key;
            this.typeModel = 'edit';
            this.addScrenn = row.title;
            this.dialogVisibleAdd = !this.dialogVisibleAdd;
        },

        /**
         * 新增_编辑/表单场景
         */
        fnConfirmScrenn () {
            if (this.addScrenn == '') {
                this.$message({
                    type: 'waring',
                    message: '表达场景名称不可以为空',
                    center: true
                });
                return;
            }

            if (this.typeModel == 'add') {
                this.$post('/student/custom_form_custom_scene%5Cadd',{
                    title: this.addScrenn
                }, resp=>{
                    if (resp.code == 1) {
                        this.getCustomList();
                        this.dialogVisibleAdd = !this.dialogVisibleAdd;
                        this.$message({
                            type: 'success',
                            message: '新增成功',
                            center: true
                        });
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'waring',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            } else if (this.typeModel == 'edit') {
                this.$post('/student/custom_form_custom_scene%5Cset',{
                    scene_key: this.scene,
                    title: this.addScrenn
                }, resp=>{
                    if (resp.code == 1) {
                        this.getCustomList();
                        this.dialogVisibleAdd = !this.dialogVisibleAdd;
                        this.$message({
                            type: 'success',
                            message: '编辑成功',
                            center: true
                        });
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'waring',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            }
        },

        /**
         * 删除表单场景
         */
        fnDeleteScren (row) {
            this.$confirm('是否要删除此表单场景？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/custom_form_custom_scene%5Cdelete',{
                    scene_key: row.scene_key
                },resp=>{
                    if (resp.code == 1) {
                        this.getCustomList();
                        this.$message({
                            type: 'success',
                            message: '删除成功',
                            center: true
                        });
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'waring',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            });
        },

        /**
         * 移除表单
         */
        fnRemoveFoem (item,row) {
            this.$confirm('将此表单移除会影响表单的收集，是否继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/custom_form%5Cset_scene',{
                    form_no: row.form_no,
                    scene: item.scene,
                    type: 2
                },resp=>{
                    if (resp.code == 1) {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '移除成功',
                            center: true
                        });
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'waring',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            });
        },

        /**
         * 添加表单
         */
        fnAddForm () {
            this.showAddDialog = !this.showAddDialog;
        },

        /**
         * 排序
         */
        handleSortChanged(data) {
            let sortTypeMap = {
                ascending: 'asc',
                descending: 'desc'
            };

            let sortFieldMap = {
            };

            if (data.order) {
                this.filterData.sort_field = sortFieldMap[data.prop];
                this.filterData.sort_type = sortTypeMap[data.order];
            } else {
                this.filterData.sort_field = '';
                this.filterData.sort_type = '';
            }

            this.getTableData();
        },

        /**
         * 获取选择表单
         */
        fnGetSimaple () {
            if (this.dynamicTags.length == 0) {
                this.dynamicTags.push(this.simple.split('&')[0]);
                this.form_no = this.simple.split('&')[1];
                this.ifSimple = true;
            } else {
                this.$message({
                    type: 'waring',
                    message: '仅支持添加一个表单'
                });
                return;
            }
        },

        /**
         * 移除添加表单
         */
        handleClose () {
            this.dynamicTags = [];
            this.ifSimple = false;
            this.ifSimple = true;
        },

        /**
         * 提交表单
         */
        subMitForm () {
            let scene = null;

            if (this.sceneType == '') {
                this.$message({
                    type: 'waring',
                    message: '表单场景不可以为空',
                    center: true
                });
                return;
            }

            if (this.dynamicTags.length < 1) {
                this.$message({
                    type: 'waring',
                    message: '表单名称不可以为空',
                    center: true
                });
                return;
            }

            for(let i=0; i<this.tableData.length; i++) {
                if (this.tableData[i].scene == this.sceneType && this.tableData[i].custom_form_list.length > 0) {
                    this.$message({
                        type: 'waring',
                        message: '该场景下，同时只能有一个表单',
                        center: true
                    });
                    return;
                }
            }

            this.$post('/student/custom_form%5Cset_scene',{
                form_no: this.form_no,
                scene: this.sceneType,
                type: 1
            },resp=>{
                if (resp.code == 1) {
                    this.showAddDialog = !this.showAddDialog;
                    this.getTableData();
                    this.$message({
                        type: 'success',
                        message: '添加成功',
                        center: true
                    });
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'waring',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },

        /**
         * 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        },

        /**
         * 移除已选表单
         */
        deleteForm(){
            this.form_no = '';
            this.dynamicTags = [];
            this.simple = '';
            this.ifSimple = false;
        },
    }
};
</script>

<style lang="less" scoped>
    .container {
        background-color: #fff;
        padding: 10px 15px 15px 15px;
        display: flex;
        flex-direction: column;
        position: relative;
        width: 100%;
        .headers {
            margin-bottom: 10px;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .header-right {
                display: flex;
                .el-button {
                    margin-left: 20px;
                }
            }
        }
        .curse-add {
            color: rgb(64, 158, 255);
            cursor: pointer;
        }
        .pagination-wrapper {
            padding-top: 10px;
            .el-pagination {
                float: right;
                padding: 0;
                background-color: transparent;
            }
        }
        .dialog-footer {
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
    .el-tag + .el-tag {
        margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .preview-qr-wrap {
        width: 120px;
        height: 120px;
        text-align: center;
        margin: 0 auto;
        img {
        width: 100%;
        height: 100%;
        }
    }
    .preview-qr {
        text-align: center;
    }
    .dialog_cont {
        display: flex;
        height: 32px;
        align-items: center;
        margin-bottom: 20px;
    }
    .text_form{
        max-width: 130px;
        height: 15px;
        display: inline-block;
        margin-right: 8px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        vertical-align: middle;
    }
    .el-icon-delete{
        cursor: pointer;
        vertical-align: middle;
    }
    .el-table-title {
        margin-top: 30px;
        margin-bottom: 10px;
    }
    .reference {
        border: none;
        background: transparent !important;
        position: relative;
        top: 3px;
        left: -10px;
        // display: flex;
        // justify: center;
        // align-items: center;
    }
    .el-screnn-dialog {
        display: flex;
        height: 32px;
        align-items: center;
    }
</style>
<style lang="less">
    .formScene .el-table__body-wrapper .el-table__body .el-table__row td {
        border-right: none;
    }
    .formScene .el-table__header-wrapper .el-table__header .has-gutter tr th {
        border-right: none;
    }
    .formScene .el-table .el-table_1_column_6  .cell {
        position: relative;
    }
    .el-popover {
        text-align: center !important;
    }
    .formScene .dialog-footer {
        justify-content: space-evenly !important;
    }
    .pagination-wrapper {
        padding-top: 10px;
        .el-pagination {
            float: right;
            margin-top: 0px !important;
            padding: 0;
            background-color: transparent;
        }
    }
</style>
